/*
 * XMLConverter.java
 *
 * Created on April 20, 2007, 4:40 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package org.voidness.twittava.conversion.converters;

import java.io.StringReader;
import java.util.ArrayList;
import java.util.Collection;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.voidness.twittava.domain.Status;
import org.voidness.twittava.domain.StatusUser;

/**
 *
 * @author void
 */
public class XMLConverter implements Converter {
    
    public Document getDocument(String data) {
        SAXBuilder builder = new SAXBuilder();
        try {
            return builder.build(new StringReader(data));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    
    private Status statusFromElement(Element obj) throws Exception {
        Status status = new Status();
        status.setId(Integer.parseInt(obj.getChild("id").getTextNormalize()));
        status.setText(obj.getChild("text").getTextNormalize());
        status.setCreationDate(obj.getChild("created_at").getTextNormalize());
        status.setUser(userFromElement(obj.getChild("user")));
        return status;
    }
    
    private StatusUser userFromElement(Element obj) throws Exception {
        StatusUser user = new StatusUser();
        user.setId(Integer.parseInt(obj.getChild("id").getTextNormalize()));
        user.setName(obj.getChild("name").getTextNormalize());
        user.setScreenName(obj.getChild("screen_name").getTextNormalize());
        user.setDescription(obj.getChild("description").getTextNormalize());
        user.setLocation(obj.getChild("location").getTextNormalize());
        user.setProfileImageUrl(obj.getChild("profile_image_url").getTextNormalize());
        user.setUrl(obj.getChild("url").getTextNormalize());
        return user;
    }
    
    public Collection<Status> convertTimeline(String data) throws Exception {
        Collection<Status> statuses = new ArrayList<Status>();
        Document xmlDocument = getDocument(data);
        Element statusesElement = xmlDocument.getRootElement();
        for (Object statusElement : statusesElement.getChildren()){
            if (statusElement instanceof Element) {
                statuses.add(statusFromElement((Element) statusElement));
            }
        }
        return statuses;
    }
    
    public Status convertStatus(String data) throws Exception {
        Status status = new Status();
        Document xmlDocument = getDocument(data);
        Element statusElement = xmlDocument.getRootElement();
        status = statusFromElement(statusElement);
        return status;
    }
    
}
